package com.crowdfunding.controller;

import java.util.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.crowdfunding.bean.Member;
import com.crowdfunding.bean.Permission;
import com.crowdfunding.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.crowdfunding.bean.User;
import com.crowdfunding.service.UserService;
import com.crowdfunding.util.AjaxResult;
import com.crowdfunding.util.Const;
import com.crowdfunding.util.MD5Util;

@Controller
public class DispatcherController {
	@Autowired
	private UserService userService;
	@Autowired
	private MemberService memberService;
	@RequestMapping("/index")
	public String index() {
		return "index";
	}
	@RequestMapping("/login")
	public String login(HttpServletRequest request,HttpSession session) {
		String logintype=null;
		Cookie[] cookies = request.getCookies();
		if (cookies!=null){
			for (Cookie cookie :
					cookies) {
				if ("logincode".equals(cookie.getName())) {
					String logincode=cookie.getValue();
					String[]splits=logincode.split("&");
					if (splits.length==3){
						String loginacct=splits[0].split("=")[1];
						String userpswd=splits[1].split("=")[1];
						logintype=splits[2].split("=")[1];
						if ("member".equals(logintype)){
							Map<String,Object>paramMap=new HashMap<>();
							paramMap.put("loginacct", loginacct);
							paramMap.put("userpswd", userpswd);
							Member member = memberService.queryLogin(paramMap);
							if (null!=member){
								session.setAttribute(Const.LOGIN_MEMBER,member);
								return "redirect:member.htm";
							}

						}else if ("user".equals(logintype)) {
							Map<String, Object> paramMap = new HashMap<>();
							paramMap.put("loginacct", loginacct);
							paramMap.put("userpswd", userpswd);
							User user = userService.queryLogin(paramMap);
							if (null != user) {
								session.setAttribute(Const.LOGIN_USER, user);
								Permission permissionRoot=null;//根节点
								List<Permission> permissions=userService.queryPermissionsByUser(user.getId());
								//所有节点
								Map<Integer,Permission>permissionMap=new HashMap<>();
								Set<String>myUris=new HashSet<>();
								for (Permission childPermission :
										permissions) {
									permissionMap.put(childPermission.getId(),childPermission);
									myUris.add("/"+childPermission.getUrl());
								}
								session.setAttribute(Const.MY_URIS,myUris);
								for (Permission permission :
										permissions) {
									Permission child=permission;//子节点
									if(permission.getPid()==null){
										permissionRoot=permission;
									}else{
										Permission parent=permissionMap.get(child.getPid());//获取当前节点的父节点
										parent.getChildren().add(child);//设置父子关系
									}
								}
								session.setAttribute("permissionRoot",permissionRoot);
								return "redirect:main.htm";
							}

						}
					}
				}
			}
		}

			return "login";
	}
	@RequestMapping("/main")
	public String main() {
		return "main";
	}
	@RequestMapping("/member")
	public String member() {
		return "member";
	}
	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		session.invalidate();//销毁session对象
		return "redirect:index.htm";
	}
	//同步登录请求
	/**
	@RequestMapping("/doLogin")
	public String doLogin(String loginacct,String userpswd,String type,HttpSession session) {
		Map<String,Object>paramMap=new HashMap<>();
		paramMap.put("loginacct", loginacct);
		paramMap.put("userpswd", userpswd);
		paramMap.put("type", type);
		User user=userService.queryLogin(paramMap);
		session.setAttribute(Const.LOGIN_USER, user);
		return "redirect:main.htm";
	}
	 */
	@ResponseBody
	@RequestMapping("doLogin")
	public Object doLogin(String loginacct, String userpswd, String type, HttpSession session,
						  String remberme, HttpServletResponse response) {
		AjaxResult result=new AjaxResult();
		try {
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("loginacct", loginacct);
			paramMap.put("userpswd", MD5Util.digest(userpswd));
			paramMap.put("type", type);

			if("member".equals(type)){

				Member member = memberService.queryLogin(paramMap);
				if (member!=null){
					session.setAttribute(Const.LOGIN_MEMBER, member);
					result.setSuccess(true);
				}

				if("1".equals(remberme)){
					String logincode = "\"loginacct="+member.getLoginacct()+"&userpwd="+member.getUserpswd()+"&logintype=member\"";
					//loginacct=zhangsan&userpwd=21232f297a57a5a743894a0e4a801fc3&logintype=member
					System.out.println("用户-存放到Cookie中的键值对：logincode::::::::::::"+logincode);

					Cookie c = new Cookie("logincode",logincode);

					c.setMaxAge(60*60*24*14); //2周时间Cookie过期     单位秒
					c.setPath("/"); //表示任何请求路径都可以访问Cookie

					response.addCookie(c);
				}

			}else if("user".equals(type)){
				User user = userService.queryLogin(paramMap);
				if (user!=null){
					session.setAttribute(Const.LOGIN_USER, user);
					result.setSuccess(true);

				}


				if("1".equals(remberme)){
					String logincode = "\"loginacct="+user.getLoginacct()+"&userpwd="+user.getUserpswd()+"&logintype=user\"";
					//loginacct=superadmin&userpwd=21232f297a57a5a743894a0e4a801fc3&logintype=user
					System.out.println("用户-存放到Cookie中的键值对：logincode::::::::::::"+logincode);

					Cookie c = new Cookie("logincode",logincode);

					c.setMaxAge(60*60*24*14); //2周时间Cookie过期     单位秒
					c.setPath("/"); //表示任何请求路径都可以访问Cookie

					response.addCookie(c);
				}

				//---------------------

				//加载当前登录用户的所拥有的许可权限.

				//User user = (User)session.getAttribute(Const.LOGIN_USER);

				List<Permission> myPermissions = userService.queryPermissionsByUser(user.getId()); //当前用户所拥有的许可权限

				Permission permissionRoot = null;

				Map<Integer,Permission> map = new HashMap<Integer,Permission>();

				Set<String> myUris = new HashSet<String>(); //用于拦截器拦截许可权限

				for (Permission innerpermission : myPermissions) {
					map.put(innerpermission.getId(), innerpermission);

					myUris.add("/"+innerpermission.getUrl());
				}

				session.setAttribute(Const.MY_URIS, myUris);


				for (Permission permission : myPermissions) {
					//通过子查找父
					//子菜单
					Permission child = permission ; //假设为子菜单
					if(child.getPid() == null ){
						permissionRoot = permission;
					}else{
						//父节点
						Permission parent = map.get(child.getPid());
						parent.getChildren().add(child);
					}
				}


				session.setAttribute("permissionRoot", permissionRoot);
				//---------------------
			}else{
				result.setSuccess(false);
			}

			result.setData(type);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage(e.getMessage());
		}
		return result;
	}
}
